// 提交日记表单
document.getElementById("diaryForm").addEventListener("submit", function(event) {
    event.preventDefault();

    const weather = document.getElementById("weather").value;
    const mood = document.getElementById("mood").value;
    const events = document.getElementById("events").value;
    const date = new Date().toISOString().split('T')[0]; // 获取当前日期

    const data = {
        date: date,
        weather: weather,
        mood: mood,
        events: events
    };

    fetch("http://localhost:5000/add_diary", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById("message").textContent = data.message || "日记提交成功！";
        loadDiary();  // 提交后自动更新历史日记
    })
    .catch(error => {
        document.getElementById("message").textContent = "提交失败，请稍后再试。";
    });
});

// 加载历史日记
document.getElementById("viewDiaryBtn").addEventListener("click", loadDiary);

function loadDiary() {
    fetch("http://localhost:5000/get_diary")
    .then(response => response.json())
    .then(data => {
        const diaryList = document.getElementById("diaryList");
        diaryList.innerHTML = '';  // 清空历史日记

        if (data.length === 0) {
            diaryList.innerHTML = "<p>没有历史日记。</p>";
        } else {
            data.forEach(entry => {
                const diaryItem = document.createElement("div");
                diaryItem.classList.add("diary-item");

                const date = document.createElement("div");
                date.classList.add("date");
                date.textContent = entry.date;

                const weather = document.createElement("div");
                weather.classList.add("weather");
                weather.textContent = "天气：" + entry.weather;

                const mood = document.createElement("div");
                mood.classList.add("mood");
                mood.textContent = "心情：" + entry.mood;

                const events = document.createElement("div");
                events.classList.add("events");
                events.textContent = "事件：" + entry.events;

                diaryItem.appendChild(date);
                diaryItem.appendChild(weather);
                diaryItem.appendChild(mood);
                diaryItem.appendChild(events);

                diaryList.appendChild(diaryItem);
            });
        }
    })
    .catch(error => {
        document.getElementById("diaryList").innerHTML = "<p>加载历史日记失败。</p>";
    });
}
